<template>
  <div class="resume-optimizer">
    <!-- 🎯 广告语轮播区 -->
    <div class="slogan-carousel">
      <transition name="fade" mode="out-in">
        <div :key="currentSloganIndex" class="slogan-text">
          {{ slogans[currentSloganIndex] }}
        </div>
      </transition>
    </div>

    <!-- 文件上传区域 -->
    <el-upload
      class="pdf-upload"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleFileChange"
      :disabled="!!fileName"
      accept=".pdf"
    >
      <el-button type="primary" :disabled="!!fileName">
        {{ fileName ? 'PDF 已上传' : '选择 PDF 文件（≤2MB）' }}
      </el-button>
    </el-upload>

    <!-- 显示上传的文件名 -->
    <div v-if="fileName" class="file-info">
      已选择文件：<strong>{{ fileName }}</strong>
    </div>

    <!-- 手动输入文本 -->
    <el-input
      v-model="manualInput"
      type="textarea"
      :rows="4"
      placeholder="或在此手动输入简历内容"
      class="manual-input"
      :disabled="!!fileName"
    />

    <!-- AI 优化按钮 + 清空按钮 -->
    <div style="margin-top: 16px; display: flex; gap: 12px">
      <el-button
        type="success"
        :loading="false"
        @click="handleOptimize"
        :disabled="!canOptimize || loading"
      >
        AI 优化简历
      </el-button>
      <el-button type="default" @click="handleClear">
        清空
      </el-button>
    </div>

    <div v-if="total" class="total-count">
      已优化 {{ total }} 条数据
    </div>

    <!-- 加载动画遮罩（仅在加载且无结果时显示） -->
    <div v-if="loading && optimizedData.length === 0" class="loading-overlay">
      <div class="loading-content">
        <div class="loading-text">
          AI优化中
          <span class="dot">.</span>
          <span class="dot">.</span>
          <span class="dot">.</span>
        </div>
      </div>
    </div>

    <!-- 结果展示 -->
    <el-table
      v-if="optimizedData.length > 0"
      :data="optimizedData"
      style="width: 100%; margin-top: 24px"
      max-height="600"
    >
      <el-table-column prop="before" label="优化前" width="472">
        <template #default="{ row }">
          <div class="text-cell">{{ row.before }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="after" label="优化后" width="472">
        <template #default="{ row }">
          <div class="text-cell">{{ row.after }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="55">
        <template #default="{ row }">
          <el-button type="text" size="small" @click="copyToClipboard(row.after)">
            复制
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 庆祝粒子动画容器 -->
    <div id="confetti-container" style="position: fixed; bottom: 0; left: 0; width: 100%; height: 300px; pointer-events: none; z-index: 1; overflow: hidden;"></div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { uploadPdfApi, yhjlApi } from '../api/Resume'

const loading = ref(false)
const fileName = ref('')          // 上传后返回的文件名
const manualInput = ref('')       // 用户手动输入内容
const optimizedData = ref([])     // 优化结果数组
const total = ref(0)              // 优化总条数

// 是否可以优化：只能有文件 或 手动输入，不能同时存在
const canOptimize = computed(() => {
  const hasFile = !!fileName.value
  const hasInput = !!manualInput.value.trim()
  return (hasFile || hasInput) && !(hasFile && hasInput)
})

// 广告语列表
const slogans = [
  '一键优化，让简历闪闪发光✨',
  'AI 精修简历，面试邀约翻倍🚀',
  '智能重塑简历，让机会主动找你🎯',
  '你负责才华，我负责表达💡',
  '简历太普通？AI 来开挂！🤖',
  'AI 智能优化简历，让每一段经历都打动HR💼'
]

const currentSloganIndex = ref(0)

// 自动轮播
onMounted(() => {
  const interval = setInterval(() => {
    currentSloganIndex.value = (currentSloganIndex.value + 1) % slogans.length
  }, 4000) // 每 4 秒切换

  onBeforeUnmount(() => {
    clearInterval(interval)
  })
})

// 清空所有内容
const handleClear = () => {
  fileName.value = ''
  manualInput.value = ''
  optimizedData.value = []
  total.value = 0
  ElMessage.info('已清空内容')
}

// 处理文件选择
const handleFileChange = (file) => {
  const { raw } = file

  if (raw.type !== 'application/pdf') {
    ElMessage.error('仅支持 PDF 文件！')
    return
  }

  if (raw.size > 2 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过 2MB！')
    return
  }

  // 重置状态（保留当前 manualInput 不清空，由用户决定）
  optimizedData.value = []
  total.value = 0

  uploadFileAndGetFilename(raw)
}

// 上传文件并设置 fileName
const uploadFileAndGetFilename = async (file) => {
  const formData = new FormData()
  formData.append('file', file)
  try {
    const res = await uploadPdfApi(formData)
    fileName.value = res.data
    ElMessage.success('文件上传成功')
  } catch (err) {
    ElMessage.error('文件上传失败')
    console.error(err)
  }
}

// 复制文本到剪贴板（兼容现代和旧浏览器）
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制到剪贴板')
  } catch (err) {
    const textarea = document.createElement('textarea')
    textarea.value = text
    textarea.setAttribute('readonly', '')
    textarea.style.position = 'absolute'
    textarea.style.left = '-9999px'
    document.body.appendChild(textarea)
    textarea.select()
    try {
      document.execCommand('copy')
      ElMessage.success('已复制到剪贴板')
    } catch (e) {
      ElMessage.error('复制失败，请手动复制')
    }
    document.body.removeChild(textarea)
  }
}

// AI 优化逻辑
const handleOptimize = async () => {
  const hasFile = !!fileName.value
  const hasInput = !!manualInput.value.trim()

  if (hasFile && hasInput) {
    ElMessage.warning('请仅使用文件上传或手动输入中的一种方式')
    return
  }

  optimizedData.value = []
  total.value = 0
  loading.value = true

  const payload = {
    file: fileName.value || '',
    userPrompt: manualInput.value || ''
  }

  try {
    const res = await yhjlApi(payload)
    if (res.code === 1) {
      optimizedData.value = res.data.rows
      total.value = res.data.total
      ElMessage.success('AI 优化成功！')
      fileName.value = ''
      manualInput.value = ''
      // 🎉 触发庆祝动画
      launchConfetti()
    } else {
      ElMessage.error('优化结果格式异常')
    }
  } catch (err) {
    ElMessage.error('AI 优化失败，请重试')
    console.error(err)
  } finally {
    loading.value = false
  }
}

// 🎉 礼花粒子动画函数
const launchConfetti = () => {
  const container = document.getElementById('confetti-container')
  if (!container) return

  container.innerHTML = ''
  const canvas = document.createElement('canvas')
  canvas.width = window.innerWidth
  canvas.height = 300
  canvas.style.position = 'absolute'
  canvas.style.bottom = '0'
  canvas.style.left = '0'
  container.appendChild(canvas)

  const ctx = canvas.getContext('2d')
  const particles = []
  const glitterParticles = [] // ✨ 新增：闪光粒子数组

  const colors = ['#ff9ff3', '#feca57', '#ff6b6b', '#48dbfb', '#1dd1a1', '#f368e0', '#ff9f43']
  const glitterColors = ['#ffffff', '#fff9c4', '#ffd54f'] // 闪光色
  const shapes = ['circle', 'rect', 'triangle']

  // 创建主粒子
  const createParticle = (side) => {
    const startX = side === 'left' ? 50 : canvas.width - 50
    const startY = canvas.height

    const centerX = canvas.width / 2
    const centerY = -100 // 飞得更高！

    const dx = centerX - startX
    const dy = centerY - startY
    const dist = Math.sqrt(dx * dx + dy * dy)
    const baseSpeed = 8 + Math.random() * 5

    let vx = (dx / dist) * baseSpeed
    let vy = (dy / dist) * baseSpeed

    vx += (Math.random() - 0.5) * 2
    vy += (Math.random() - 0.5) * 1.5

    return {
      x: startX,
      y: startY,
      vx,
      vy,
      gravity: 0.08,
      drag: 0.975,
      size: Math.random() * 6 + 3,
      color: colors[Math.floor(Math.random() * colors.length)],
      shape: shapes[Math.floor(Math.random() * shapes.length)],
      opacity: 1,
      decay: Math.random() * 0.014 + 0.008,
      rotation: Math.random() * 360,
      rotationSpeed: (Math.random() - 0.5) * 8,
      // ✨ 每帧有概率生成闪光粒子
      shouldSpawnGlitter: Math.random() > 0.7
    }
  }

  // ✨ 创建闪光粒子（从主粒子位置溅射）
  const createGlitter = (x, y) => {
    return {
      x,
      y,
      vx: (Math.random() - 0.5) * 3,
      vy: (Math.random() - 0.5) * 3,
      gravity: 0.05,
      drag: 0.96,
      size: Math.random() * 1.5 + 0.5, // 很小！
      color: glitterColors[Math.floor(Math.random() * glitterColors.length)],
      opacity: Math.random() * 0.6 + 0.4, // 初始半透明
      decay: Math.random() * 0.03 + 0.02 // 消失更快
    }
  }

  // 发射主粒子
  for (let i = 0; i < 60; i++) {
    const side = i % 2 === 0 ? 'left' : 'right'
    particles.push(createParticle(side))
  }

  // 动画循环
  const animate = () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    // ✨ 更新闪光粒子
    glitterParticles.forEach((g, i) => {
      g.vy += g.gravity
      g.vx *= g.drag
      g.vy *= g.drag
      g.x += g.vx
      g.y += g.vy
      g.opacity -= g.decay

      if (g.opacity > 0 && g.y < canvas.height + 50) {
        ctx.globalAlpha = g.opacity
        ctx.fillStyle = g.color
        ctx.beginPath()
        ctx.arc(g.x, g.y, g.size, 0, Math.PI * 2)
        ctx.fill()
      } else {
        glitterParticles.splice(i, 1) // 移除死亡粒子
      }
    })

    // 更新主粒子
    let alive = false
    particles.forEach(p => {
      p.vy += p.gravity
      p.vx *= p.drag
      p.vy *= p.drag
      p.x += p.vx
      p.y += p.vy
      p.rotation += p.rotationSpeed
      p.opacity -= p.decay

      // ✨ 随机生成闪光粒子（从主粒子当前位置）
      if (p.shouldSpawnGlitter && Math.random() > 0.85) {
        glitterParticles.push(createGlitter(p.x, p.y))
      }

      if (p.opacity > 0 && p.y < canvas.height + 100) {
        alive = true
        ctx.save()
        ctx.globalAlpha = p.opacity
        ctx.fillStyle = p.color
        ctx.translate(p.x, p.y)
        ctx.rotate((p.rotation * Math.PI) / 180)

        if (p.shape === 'circle') {
          ctx.beginPath()
          ctx.arc(0, 0, p.size, 0, Math.PI * 2)
          ctx.fill()
        } else if (p.shape === 'rect') {
          ctx.fillRect(-p.size / 2, -p.size / 2, p.size, p.size)
        } else if (p.shape === 'triangle') {
          ctx.beginPath()
          ctx.moveTo(0, -p.size)
          ctx.lineTo(-p.size, p.size)
          ctx.lineTo(p.size, p.size)
          ctx.closePath()
          ctx.fill()
        }
        ctx.restore()
      }
    })

    // 继续动画，直到所有粒子消失
    if (alive || glitterParticles.length > 0) {
      requestAnimationFrame(animate)
    } else {
      container.innerHTML = ''
      // 可选：释放音频上下文（通常不需要）
    }
  }

  animate()
}

</script>

<style scoped>
/* 主容器 */
.resume-optimizer {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.pdf-upload {
  margin-bottom: 12px;
}

.file-info {
  margin-bottom: 16px;
  color: #606266;
}

.manual-input {
  margin-top: 12px;
}

.total-count {
  margin-top: 12px;
  font-size: 15px;
  font-weight: 600;
  color: #409eff;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.total-count::before {
  content: '✓';
  color: #67c23a;
  font-weight: bold;
  font-size: 16px;
}

.text-cell {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.5;
}

/* 广告语轮播样式 —— 带流动渐变背景 */
.slogan-carousel {
  position: relative;
  width: 100%;
  height: 56px; /* 固定高度，避免轮播时跳动 */
  margin-bottom: 24px;
  border-radius: 8px;
  overflow: hidden;
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 渐变背景层（与 loading-overlay 一致） */
.slogan-carousel::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    120deg,
    #409eff,
    #8e44ad,
    #e74c3c,
    #f39c12,
    #2ecc71,
    #3498db,
    #9b59b6
  );
  background-size: 500% 500%;
  animation: gradientFlow 6s ease infinite;
  opacity: 0.35;
  z-index: 1;
}

/* 轮播文字容器 */
.slogan-text {
  position: relative;
  z-index: 2;
  font-size: 18px;
  font-weight: 600;
  color: white;
  text-align: center;
  padding: 8px 24px;
  background: rgba(255, 255, 255, 0);
  backdrop-filter: blur(6px);
  border-radius: 20px;
  line-height: 1.4;
}

/* 淡入淡出过渡 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* ————————————————————————————————
   加载遮罩层：AI优化中动画（无旋转，强渐变）
   ———————————————————————————————— */

.loading-overlay {
  position: relative;
  width: 100%;
  height: 300px;
  margin-top: 24px;
  border-radius: 8px;
  overflow: hidden;
  background: #f0f2f5; /* 稍深底色，衬托渐变更明显 */
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 背景层：强对比线性渐变流动（无旋转） */
.loading-overlay::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    120deg,
    #409eff,
    #8e44ad,
    #e74c3c,
    #f39c12,
    #2ecc71,
    #3498db,
    #9b59b6
  );
  background-size: 500% 500%;
  animation: gradientFlow 6s ease infinite;
  opacity: 0.35; /* 控制整体透明度，避免过亮 */
  z-index: 1;
}

/* 文字内容区 */
.loading-content {
  position: relative;
  z-index: 2;
}

.loading-text {
  font-size: 20px;
  font-weight: 600;
  color: white;
  text-align: center;
  padding: 16px 32px;
  background: rgba(70, 58, 58, 0);
  backdrop-filter: blur(6px);
  border-radius: 24px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.dot {
  display: inline-block;
  opacity: 0;
  animation: dotPulse 1.4s infinite;
  animation-delay: 0s;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes gradientFlow {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes dotPulse {
  0%, 100% {
    opacity: 0;
    transform: scale(0.8);
  }
  50% {
    opacity: 1;
    transform: scale(1.2);
  }
}

/* ————————————————————————————————
   旧版加载 spinner（保留但未使用，可安全保留）
   ———————————————————————————————— */

.gradient-spinner {
  width: 18px;
  height: 18px;
  border: 2px solid transparent;
  border-top-color: #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  position: relative;
}

.gradient-spinner::before {
  content: '';
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  border-radius: 50%;
  background: conic-gradient(
    from 0deg,
    #409eff,
    #8e44ad,
    #e74c3c,
    #f39c12,
    #2ecc71,
    #409eff
  );
  -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  -webkit-mask-composite: destination-out;
  mask-composite: exclude;
  animation: rotate 1.5s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}
</style>